﻿namespace EventBusNet6
{
    public class CommandHostService : BackgroundService
    {
        private readonly Serilog.ILogger _logger = Log.Logger;

        protected override  Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Func<IExecuteCommand, bool> canExcute =  (cmd) =>
            {
                //Console.WriteLine("已经存在这个文件了");
                //return !File.Exists(cmd.OutputFile);
                return true;
            };

            Action<IExecuteCommand> onCompleted = async (cmd) =>
            {
                try
                {
                    _logger.Information($"guid={cmd.Guid} \r {cmd.OutData.ToString()}");
                    //Console.WriteLine("执行完成，需要处理其他事情");
                    if (!string.IsNullOrWhiteSpace(cmd.NoticeUrl))
                    {
                        await cmd.NoticeUrl.PostJsonAsync(new { guid = cmd.Guid, catalogfile = cmd.OutputFile, sendtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") });
                    }
                    if (!string.IsNullOrWhiteSpace(cmd.Rename))
                    {
                        DirectoryInfo dirinfo = new DirectoryInfo(cmd.OutputFile);
                        if (dirinfo.Exists)
                        {
                            string path = Path.Combine(cmd.OutputFile, cmd.Rename);
                            for (int i = 0; i < dirinfo.GetFiles().Length; i++)
                            {
                                var  item = dirinfo.GetFiles()[i];
                                item.MoveTo(path);
                            }
                        }  
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.ToString());
                   
                }
            };
            Task.Run(() => { CommandService.GetInstance().RunAsync(stoppingToken, canExcute, onCompleted); });
            return  Task.CompletedTask;
        }

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.Information(nameof(CommandHostService) + " is starting.");
            return base.StartAsync(cancellationToken);
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.Information(nameof(CommandHostService) + " is stopping.");
            return base.StopAsync(cancellationToken);
        }
    }
}
